package doctor_dao

import (
	"gorm.io/gorm/clause"
	"jjqzplucky.site/sz-core/internal/models"
	doctor_model "jjqzplucky.site/sz-core/internal/models/doctor"
)

type Doctor = doctor_model.Doctor
type DoctorVo = doctor_model.DoctorVO

// SaveDoctor 创建/更新医生
func SaveDoctor(d *Doctor) error {
	var err error
	if(d.Id == 0){
		err = models.DB.Create(&d).Error
	}else{
		err = models.DB.Omit("create_time").Save(&d).Error
	}
	return err
}

// GetDoctorByID 根据id获取医生信息
func GetDoctorByID(d *Doctor) error {
	err := models.DB.Take(d).Error
	return err
}

// Page 查询医生分页信息
func Page(param *doctor_model.QueryParams) ([]DoctorVo, error) {
	query := models.DB.Table("doctor d").
		Joins("LEFT JOIN medical_dept_sub_and_doctor sd ON sd.doctor_id = d.id").
		Joins("LEFT JOIN medical_dept_sub ds ON sd.dept_sub_id = ds.id").
		Joins("LEFT JOIN medical_dept md ON ds.dept_id = md.id")
	if param.Name != nil {
		query = query.Clauses(clause.Like{Column: "d.name", Value: "%" + *param.Name + "%"})
	}
	if param.Degree != nil {
		query = query.Where("d.degree = ?", *param.Degree)
	}
	if param.Job != nil {
		query = query.Where("d.job =?", *param.Job)
	}
	if param.Recommended != nil {
		query = query.Where("d.recommended =?", *param.Recommended)
	}
	if param.Status != nil {
		query = query.Where("d.status =?", *param.Status)
	}
	if param.DeptId != nil {
		query = query.Where("md.id =?", *param.DeptId)
	}
	if param.Page != 0 {
		query = query.Offset((param.Page - 1) * param.PageSize)
	} else {
		query = query.Offset(0)
	}
	if param.PageSize != 0 {
		query = query.Limit(param.PageSize)
	} else {
		query = query.Limit(10)
	}
	query = query.Select(`
	d.id as id, d.name as name, d.sex as sex, d.tel as tel, d.school as school, d.degree as degree, d.job as job, d.status as status, 
	d.create_time as create_time,
	d.update_time as update_time,
	d.delete_time as delete_time,
	md.name as dept_name, 
	ds.name as sub_name
	`)
	// 执行查询
	var doctors []DoctorVo
	err := query.Count(&param.Total).Find(&doctors).Error
	return doctors, err
}


//根据id删除
func DeleteById(id uint64) error {
	return models.DB.Delete(&Doctor{}, id).Error
}